﻿@{
    ViewBag.Title = "Исходящие накладные";
    Layout = "~/Views/Shared/_Layout.cshtml";
}

<style>
    .form-horizontal .controls {
      /*original: margin-left: 160px;*/
      margin-left: 120px;
    }
</style>

<header class="jumbotron subhead" id="overview">
    <h1></h1>
    <p class="lead">Исходящие накладные</p>
</header>

<div class="page">

    <div class="block" id="start-page"></div>
    <div class="block" id="invoice-edit-page"></div>
    <div class="block" id="invoice-line-edit-page"></div>
    <div class="block alert alert-error" id="error-page"></div>

</div>

<script type="text/template" class="template-start-page">
    
    <div class="form-actions">
        <a href="javascript:void(0);" class="btn" data-action="refreshInvoiceTable">
            <i class="icon-refresh"></i> Обновить</a>
        <a href="javascript:void(0);" class="btn" data-action="toggleSearchBlock">
            Настройки поиска</a>

        <div class="pull-right">
            <a href="javascript:void(0);" class="btn btn-success" data-action="goToInvoiceNewPage">
                <i class="icon-plus"></i> Создать новую накладную</a>
        </div>
    </div>

    <div class="hide" id="invoiceSearchBlock">
        <form name="INVOICES-FILTER" class="form-horizontal well" method="post">

            <input type="hidden" name="CUSTOMER_GUID" value="" />
            <input type="hidden" name="LOCATION_GUID" value="" />

            <div class="control-group"> 
                <label class="control-label" for="CUSTOMER_NAME">Получатель</label>
                <div class="controls row-fluid">
                    <input type="text" class="input-large" name="CUSTOMER_NAME" value="" placeholder="Компания получатель">
                </div> 
            </div>                                         
                        
            <div class="control-group"> 
                <label class="control-label" for="LOCATION_NAME">Склад</label>
                <div class="controls row-fluid">
                    <input type="text" class="input-large" name="LOCATION_NAME" value="" placeholder="Склад получателя" />
                </div> 
            </div>  
    
            <div class="control-group"> 
                <label class="control-label" for="DOC_DATE_START">Дата</label>
                <div class="controls">
                    <div id="dt1" class="input-append date" data-date="" data-date-format="dd.mm.yyyy">
                        <input type="text" class="input-small" name="DOC_DATE_START" value="" placeholder="дд.мм.гггг" />
                        <span class="add-on"><i class="icon-th"></i></span>
                    </div>
                    <div id="dt1" class="input-append date" data-date="" data-date-format="dd.mm.yyyy">
                        <input type="text" class="input-small" name="DOC_DATE_END" value="" placeholder="дд.мм.гггг" />
                        <span class="add-on"><i class="icon-th"></i></span>
                    </div>
                </div> 
            </div>    
 
            <div class="control-group"> 
                <label class="control-label" for="DOC_NUMBER">№</label>
                <div class="controls">
                    <input type="text" class="input-small" name="DOC_NUMBER" value="" />
                </div> 
            </div>                                 
                        
            <div class="control-group"> 
                <label class="control-label" for="IS_ALL">Обработанные</label>
                <div class="controls row-fluid">
                    <input type="checkbox" name="IS_ALL" />
                </div> 
            </div>  

        </form>
    </div>

    <div id="data-table"></div>
    
</script>

<script type="text/template" class="template-invoice-edit-page">

    <div class="form-actions">
        <a href="javascript:void(0);" class="btn" data-action="back">
            <i class="icon-circle-arrow-left"></i> Назад</a>
    
        <div class="pull-right">
            <a href="javascript:void(0);" class="btn btn-danger" data-action="removeInvoice">
                <i class="icon-remove"></i> Удалить</a>
            <a href="javascript:void(0);" class="btn btn-success" data-action="addInvoiceLine">
                <i class="icon-plus"></i> Добавить позицию</a>
            <a href="javascript:void(0);" class="btn btn-primary" data-action="saveInvoice">
                Сохранить</a>
        </div>
    </div>

    <div id="data-invoice"></div>

</script>

<script type="text/template" class="template-invoice-line-edit-page">

    <div class="form-actions">
        <a href="javascript:void(0);" class="btn" data-action="back">
            <i class="icon-circle-arrow-left"></i> Назад</a>
    
        <div class="pull-right">
            <a href="javascript:void(0);" class="btn btn-danger" data-action="removeInvoiceLine">
                <i class="icon-remove"></i> Удалить</a>
            <a href="javascript:void(0);" class="btn btn-primary" data-action="saveInvoiceLine">
                Сохранить</a>
        </div>
    </div>

    <div id="data-invoice-line"></div>

</script>

<script type="text/javascript">

    $(function () {

        var view_StartPage = Backbone.View.extend({
            el: $("#start-page"),

            template: _.template($("script.template-start-page").html()),

            render: function () {
                $(this.el).html(this.template());
                this.refreshInvoiceTable();
            },

            events: {
                "click .btn[data-action='goToInvoiceNewPage']": "goToInvoiceNewPage",
                "click .btn[data-action='refreshInvoiceTable']": "refreshInvoiceTable",
                "click .btn[data-action='toggleSearchBlock']": "toggleSearchBlock",
                "click table tbody tr": "goToInvoiceEditPage",
                "keyup.typeahead input[name='LOCATION_NAME']": "locationTypeahead",
                "keyup.typeahead input[name='CUSTOMER_NAME']": "supplierTypeahead"
            },

            goToInvoiceEditPage: function (event) {
                var id = $(event.currentTarget).attr("data-index");
                controller.navigate("!/invoice/" + id, true);
            },

            goToInvoiceNewPage: function () {
                controller.navigate("!/invoice/new", true);
            },

            toggleSearchBlock: function () {
                $("#invoiceSearchBlock").toggle();
            },

            refreshInvoiceTable: function () {
                var local_el = this.el;
                $("#error-page").hide();

                $.get("/document/OutgoingInvoices/",
                    $("form[name='INVOICES-FILTER']").serialize(),
                    function (data) {
                        $("#data-table").html(data);
                        $(local_el).show();
                        $(".tablesorter").tablesorter();
                }).error(function (data) {
                    var response = $.parseJSON(data.responseText);
                    $("#error-page").html(response.message);
                    $("#error-page").show();
                });
            },

            locationTypeahead: function (event) {
                $(event.currentTarget).typeahead({
                    source: function (typeahead, query) {

                        if (query == "") {
                            $("input[name='LOCATION_GUID']").val("");
                            return;
                        }

                        return $.get('/location/FindAndReturnJson/', { term: encodeURIComponent(query) },
                            function (data) {
                                return typeahead.process(data);
                            });
                    },
                    minLength: 3,
                    onselect: function (obj) {
                        $("input[name='LOCATION_GUID']").val(obj.id);
                    }
                });
            },

            supplierTypeahead: function (event) {
                $(event.currentTarget).typeahead({
                    source: function (typeahead, query) {

                        if (query == "") {
                            $("input[name='CUSTOMER_GUID']").val("");
                            return;
                        }

                        return $.get('/supplier/FindAndReturnJson/', { term: encodeURIComponent(query) },
                            function (data) {
                                return typeahead.process(data);
                            });
                    },
                    minLength: 3,
                    onselect: function (obj) {
                        $("input[name='CUSTOMER_GUID']").val(obj.id);
                    }
                });
            }


        });

        var view_InvoiceEditPage = Backbone.View.extend({
            el: $("#invoice-edit-page"),
            index: undefined,

            template: _.template($("script.template-invoice-edit-page").html()),

            render: function (id) {

                this.index = id;

                $(this.el).html(this.template());

                this.loadInvoice(id);
            },

            events: {
                "click .btn[data-action='back']": "back",
                "click .btn[data-action='removeInvoice']": "removeInvoice",
                "click .btn[data-action='saveInvoice']": "saveInvoice",
                "click .btn[data-action='addInvoiceLine']": "goToInvoiceLineNewPage",
                "click table tbody tr": "goToInvoiceLineEditPage",
                "keyup.typeahead input[name='LOCATION_NAME']": "locationTypeahead",
                "keyup.typeahead input[name='CUSTOMER_NAME']": "supplierTypeahead"
            },

            back: function () {
                window.history.back();
            },

            goToInvoiceLineEditPage: function (event) {
                var id = $(event.currentTarget).attr("data-index");
                controller.navigate("!/invoice/" + this.index + "/" + id, true);
            },

            goToInvoiceLineNewPage: function (event) {

                if (this.index == "new")
                    return;

                controller.navigate("!/invoice/" + this.index + "/new", true);
            },

            loadInvoice: function (id) {
                var local_el = this.el;
                $("#error-page").hide();

                $.get('/document/OutgoingInvoice/' + id, function (data) {
                    $("#data-invoice").html(data);
                    $(local_el).show();
                    $(".tablesorter").tablesorter({
                        headers: {
                            0: { sorter: 'digit' } // column number, type
                        }
                    });

                    if ($("input[name='GUID_RECORD']").val() == "") {
                        $(".btn[data-action='addInvoiceLine']").addClass("disabled");
                        $(".btn[data-action='removeInvoice']").addClass("disabled");
                    }
                }).error(function (data) {
                    var response = $.parseJSON(data.responseText);
                    $("#error-page").html(response.message);
                    $("#error-page").show();
                });
            },

            saveInvoice: function () {
                $.ajax({
                    type: 'POST',
                    url: '/document/SaveOutgoingInvoice/',
                    data: $("form[name='INVOICES']").serialize(),
                    success: function () {
                        window.history.back();
                    }
                });
            },

            removeInvoice: function () {

                if (this.index == "new")
                    return;

                $.ajax({
                    type: 'POST',
                    url: '/document/DeleteOutgoingInvoice/' + this.index,
                    success: function () {
                        window.history.back();
                    }
                });
            },

            locationTypeahead: function (event) {
                $(event.currentTarget).typeahead({
                    source: function (typeahead, query) {
                        return $.get('/location/FindAndReturnJson/', { term: encodeURIComponent(query) },
                            function (data) {
                                return typeahead.process(data);
                            });
                    },
                    minLength: 3,
                    onselect: function (obj) {
                        $("input[name='LOCATION_GUID']").val(obj.id);
                    }
                });
            },

            supplierTypeahead: function (event) {
                $(event.currentTarget).typeahead({
                    source: function (typeahead, query) {
                        return $.get('/supplier/FindAndReturnJson/', { term: encodeURIComponent(query) },
                            function (data) {
                                return typeahead.process(data);
                            });
                    },
                    minLength: 3,
                    onselect: function (obj) {
                        $("input[name='CUSTOMER_GUID']").val(obj.id);
                    }
                });
            }

        });

        var view_InvoiceLineEditPage = Backbone.View.extend({
            el: $("#invoice-line-edit-page"),

            index: undefined,
            parent_index: undefined,

            template: _.template($("script.template-invoice-line-edit-page").html()),

            render: function (id_parent, id) {

                this.index = id;
                this.parent_index = id_parent;

                $(this.el).html(this.template());

                this.loadInvoiceLine(id, id_parent);
            },

            events: {
                "click .btn[data-action='back']": "back",
                "click .btn[data-action='saveInvoiceLine']": "saveInvoiceLine",
                "click .btn[data-action='removeInvoiceLine']": "removeInvoiceLine",
                "keyup.typeahead input[name='ITEM_NAME']": "itemTypeahead"
            },

            back: function () {
                window.history.back();
            },

            loadInvoiceLine: function (id, id_parent) {
                var local_el = this.el;
                $("#error-page").hide();

                $.get('/document/OutgoingInvoiceDetails/' + id, function (data) {
                    $("#data-invoice-line").html(data);
                    $(local_el).show();

                    if ($("input[name='INVOICE_GUID']").val() == "") {
                        $("input[name='INVOICE_GUID']").val(id_parent);
                        $(".btn[data-action='removeInvoiceLine']").addClass("disabled");
                    }
                }).error(function (data) {
                    var response = $.parseJSON(data.responseText);
                    $("#error-page").html(response.message);
                    $("#error-page").show();
                });
            },

            saveInvoiceLine: function () {

                $.ajax({
                    type: 'POST',
                    url: '/document/SaveOutgoingInvoiceLine/',
                    data: $("form[name='INVOICE_LINE']").serialize(),
                    success: function () {
                        window.history.back();
                    }
                });
            },

            removeInvoiceLine: function () {

                if (this.index == "new")
                    return;

                $.ajax({
                    type: 'POST',
                    url: '/document/DeleteOutgoingInvoiceLine/' + this.index,
                    success: function () {
                        window.history.back();
                    }
                });
            },

            itemTypeahead: function (event) {
                $(event.currentTarget).typeahead({
                    source: function (typeahead, query) {
                        return $.get('/product/FindAndReturnJson/', { term: encodeURIComponent(query) },
                            function (data) {
                                return typeahead.process(data);
                            });
                    },
                    minLength: 3,
                    onselect: function (obj) {
                        $("input[name='ITEM_GUID']").val(obj.id);
                    }
                });
            }

        });
        
        var Views = {
            startPage: new view_StartPage(),
            invoiceEditPage: new view_InvoiceEditPage(),
            invoiceLineEditPage: new view_InvoiceLineEditPage()
        };




        var Controller = Backbone.Router.extend({
            routes: {
                "": "start", // Пустой hash-тэг
                "!/": "start", // Начальная страница
                "!/invoice/:id": "editInvoice",                   // Блок редактирования накладной
                "!/invoice/:id_parent/:id": "editInvoiceLine"    // Блок редактирования позиции
            },

            initialize: function (options) {

            },

            start: function () {
                $(".block").hide();

                if (Views.startPage != null) {
                    Views.startPage.render();
                }
            },

            editInvoice: function (id) {
                $(".block").hide();

                if (Views.invoiceEditPage != null) {
                    Views.invoiceEditPage.render(id);
                }
            },

            editInvoiceLine: function (id_parent, id) {
                $(".block").hide();

                if (Views.invoiceLineEditPage != null) {
                    Views.invoiceLineEditPage.render(id_parent, id);
                }
            }
        });

        var controller = new Controller(); // Создаём контроллер
        Backbone.history.start();  // Запускаем HTML5 History push 

    })

</script>